package com.example.updatedemo;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.List;

import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.util.LogUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.lidroid.xutils.sample.download.DownloadInfo;
import com.lidroid.xutils.sample.download.DownloadManager;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

/**
		* @description 弹出的快速更新电子书包所有程序的下载adapter
		* @version 2.0
		* @author panyuanyuan
		* @update 2012-9-17 下午5:34:12
		*/
public class UpdateQuickAdapter2 extends BaseAdapter {

    private final Context mContext;
    private final LayoutInflater mInflater;
    private DownloadManager downloadManager;
    private List<T_Version> mVersions;
    private Button mButton;
    

    public UpdateQuickAdapter2(Context context,DownloadManager mdownloadManager,List<T_Version> versions,Button button) {
        mContext = context;
        mInflater = LayoutInflater.from(mContext);
        downloadManager = mdownloadManager;
        mVersions = versions;
        mButton = button;
    }

    @Override
    public int getCount() {
        if (downloadManager == null) return 0;
        return downloadManager.getDownloadInfoListCount();
    }

    @Override
    public Object getItem(int i) {
        return downloadManager.getDownloadInfo(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @SuppressWarnings("unchecked")
    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        DownloadItemViewHolder holder = null;
        DownloadInfo downloadInfo = downloadManager.getDownloadInfo(i);
        if (view == null) {
            view = mInflater.inflate(R.layout.download_item, null);
            holder = new DownloadItemViewHolder(downloadInfo);
            ViewUtils.inject(holder, view);
            view.setTag(holder);
            holder.refresh();

            
        } else {
            holder = (DownloadItemViewHolder) view.getTag();
            holder.update(downloadInfo);
        }

        HttpHandler<File> handler = downloadInfo.getHandler();
        if (handler != null) {
            RequestCallBack callBack = handler.getRequestCallBack();
            if (callBack instanceof DownloadManager.ManagerCallBack) {
                DownloadManager.ManagerCallBack managerCallBack = (DownloadManager.ManagerCallBack) callBack;
                if (managerCallBack.getBaseCallBack() == null) {
                    managerCallBack.setBaseCallBack(new DownloadRequestCallBack());
                }
            }
            callBack.setUserTag(new WeakReference<DownloadItemViewHolder>(holder));
        }

        return view;
    }
    
    public class DownloadItemViewHolder {
        @ViewInject(R.id.download_name)
        TextView name;
        @ViewInject(R.id.download_state)
        TextView state;
        @ViewInject(R.id.download_pb)
        ProgressBar progressBar;
        @ViewInject(R.id.download_image)
        ImageView state_iv;
        @ViewInject(R.id.download_tv)
        TextView pro_tv;
       
        
        private DownloadInfo downloadInfo;

        public DownloadItemViewHolder(DownloadInfo downloadInfo) {
            this.downloadInfo = downloadInfo;
        }

     

        public void update(DownloadInfo downloadInfo) {
            this.downloadInfo = downloadInfo;
            refresh();
        }

        public void refresh() {
        	
        	String state_download = downloadInfo.getState().toString();
        	setView(state_download);
        	
            name.setText(downloadInfo.getFileName());
             
            state.setText(tranEn(state_download));
            
            
        }
        //根据下载状态设置view
        public void setView(String download_state)
        {
        	String str = download_state;
        	if(download_state.equals("LOADING"))
        	{
        		progressBar.setVisibility(View.VISIBLE);
        		pro_tv.setVisibility(View.VISIBLE);
        		state_iv.setVisibility(View.GONE);
        		if (downloadInfo.getFileLength() > 0) {
                	int pro = (int) (downloadInfo.getProgress() * 100 / downloadInfo.getFileLength());
                    progressBar.setProgress(pro);
                    pro_tv.setText(pro+"%"); 
                } else {
                    progressBar.setProgress(0);
                }
        		
        	}
        	else if(download_state.equals("SUCCESS"))
        	{
        		progressBar.setVisibility(View.INVISIBLE);
        		pro_tv.setVisibility(View.GONE);
        		state_iv.setVisibility(View.VISIBLE);
        		state_iv.setBackgroundResource(R.drawable.finish);	
        	}
        	else if(download_state.equals("FAILURE"))
        	{
        		
        	}
        	else if(download_state.equals("WAITING"))
        	{
        		progressBar.setVisibility(View.INVISIBLE);
        		pro_tv.setVisibility(View.GONE);
        		state_iv.setVisibility(View.VISIBLE);
        		state_iv.setBackgroundResource(R.drawable.wait);
        		
        	}
        	
			
        }
        
        public String tranEn(String download_state)
        {
        	String str = download_state;
        	if(download_state.equals("LOADING"))
        	{
        		str = "正在下载";
        	}
        	else if(download_state.equals("SUCCESS"))
        	{
        		str = "下载完成";
        	}
        	else if(download_state.equals("FAILURE"))
        	{
        		str = "下载失败";
        	}
        	else if(download_state.equals("WAITING"))
        	{
        		str = "等待下载";
        	}
        	
			return str;
        }
    }

    private class DownloadRequestCallBack extends RequestCallBack<File> {
        
        @SuppressWarnings("unchecked")
        private void refreshListItem() {
            if (userTag == null) return;
            WeakReference<DownloadItemViewHolder> tag = (WeakReference<DownloadItemViewHolder>) userTag;
            DownloadItemViewHolder holder = tag.get();
            if (holder != null) {
                holder.refresh();
            }
        }

        @Override
        public void onStart() {
            refreshListItem();
        }

        @Override
        public void onLoading(long total, long current, boolean isUploading) {
            refreshListItem();
        }

        @Override
        public void onSuccess(ResponseInfo<File> responseInfo) {
        
        	
        	
        	List<DownloadInfo> downloadInfoList = downloadManager.getDownloadInfoList();
        	System.out.println("downloadInfoList--------"+downloadInfoList);
        	int j = 0;
        	for (int i = 0; i < downloadInfoList.size(); i++) {
				if(downloadInfoList.get(i).getState().toString().equals("SUCCESS"))
				{
					j++;
				}	
			}
        	System.out.println("j-----------"+j);
        	if(j==downloadInfoList.size())
        	{
//        		mButton.setText("下载完成");
        		mButton.setBackgroundResource(R.drawable.btn_done_download);
        		for (int i = 0; i < mVersions.size(); i++) {
        			T_Version t_version = mVersions.get(i);
        			String savepath = t_version.getSavepath();
        			PackageInfo info = Utils.getPackageInfo(savepath, mContext);
        			if(info != null){  
        	            ApplicationInfo appInfo = info.applicationInfo;  
        	              
        	            String packageName = appInfo.packageName;  //得到安装包名称
        	            String version=info.versionName;       //得到版本信息       
        	            t_version.setProduct(packageName);
        	            t_version.setVersion(version);
        	        }
				}
        		UpdateActivity.btn_state = "install";
        	}
        	
            refreshListItem();
        }

        @Override
        public void onFailure(HttpException error, String msg) {
            refreshListItem();
        }

        @Override
        public void onStopped() {
            refreshListItem();
        }
    }

    
}


